package com.api.shopapi.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author maochuan
 */
@Component
@ServerEndpoint("/websocket/{sid}")
@Slf4j
public class WebSocket {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public static void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 发送给全部用户
     *
     * @param message
     */
    public void sendInfoToAll(String message) {
        for (Session session : sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean isExit(String userName) {
        Session session = sessionPools.get(userName);
        if (session == null) {
            return false;
        }
        return true;
    }

    public static boolean getSessionById(String userName) {
        Session session1 = sessionPools.get(userName);
        if (session1 != null) {
            return false;
        }
        return true;
    }

    //给指定用户发送信息
    public static void sendInfoToOne(String userName, String message) {
        for (String key : sessionPools.keySet()) {
            String member = key.split("[|]")[0];
            if (member.equals(userName)) {
                try {
                    sendMessage(sessionPools.get(key), message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
//        Session session = sessionPools.get(userName);
//        try {
//            sendMessage(session, message);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String userName) {
//        String member = userName.split("[|]")[0];
        sessionPools.put(userName, session);
        addOnlineCount();
//         System.out.println(userName + "加入webSocket！当前人数为" + onlineNum);
        try {
            sendMessage(session, "欢迎" + userName + "加入连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam(value = "sid") String userName) {
        sessionPools.remove(userName);
        subOnlineCount();
//         System.out.println(userName + "断开webSocket连接！当前人数为" + onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException {
        JSONObject jsonObject = JSONObject.parseObject(message);
        String userName = jsonObject.getString("userName");
        String msg = jsonObject.getString("msg");
        sendInfoToOne(userName.split("[|]")[0], msg + ":" + userName);
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }


    @Value("${my.elderlyAlarm}")
    protected String path1;

    /**
     * 定时读取文件
     */
    @Scheduled(fixedRate = 3000)
    public void readFile() {
        traverseFolder2(path1);
    }


    public static void traverseFolder2(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        String staffCode = file2.getAbsolutePath().substring(file2.getAbsolutePath().lastIndexOf("\\") + 1);
                        traverseFolder3(file2.getAbsolutePath(), staffCode);
                    }
                }
            }
        } else {
            //System.out.println("文件不存在!");
        }
    }

    public static void traverseFolder3(String path, String staffCode) {
        int index = 0;
        for (String key : sessionPools.keySet()) {
            String member = key.split("[|]")[0];
            if (member.equals(staffCode)) {
                index++;
            }
        }
        if (index == 0) {
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                return;
            } else {
                for (File file2 : files) {
                    String fileName = file2.getName();
                    String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if (fileType.equals("txt")) {
                        String res = readTxtFile(file2.getAbsolutePath());
                        sendInfoToOne(staffCode, res);
                        file2.delete();
                    }
                }
            }
        } else {
            // System.out.println("文件不存在!");
        }
    }

    /**
     * 读取txt文件的内容
     *
     * @param fileAdress
     */
    public static String readTxtFile(String fileAdress) {
        //System.out.println("txt文件路径"+fileAdress);
        File file = new File(fileAdress);

        StringBuilder result = new StringBuilder();
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");//构造一个BufferedReader类来读取文件
            BufferedReader br = new BufferedReader(isr);
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // System.out.println(result);
        return result.toString();
    }

}
